<?php
class AdSaveEditAction extends AdminAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'json';
	}
	
	protected function afterConstruct()
	{
		$this->parseDtds('ad','edit');
	}
	
	public function execute()
	{
		$id = $this->context->post('id');
		
		$data = $this->getValidData();
		
		
		$adService = new BaseDbService('ad');
		$adPositionService = new BaseDbService('ad_position');
		
		$position = $adPositionService->get($data['position']);
		if(empty($position))
		{
			$this->data['error_messages']['position'] = array('error'=>'请选择广告所在位置');
		}
		else
		{
			$data['template'] = $position['template'];
		}
		
		if(empty($this->data['error_messages']))
		{
			if(is_numeric($id) && $id)
			{
				$adService->update($id, $data);
				$this->code	= 200;
			}
			else
			{
				$id	= $adService->add($data);
				if($id)
				{
					$this->code	= 200;
				}
				else
				{
					$this->code	= 400;
				}
			}
			
			AdminUtil::clearAdCache();
		}
		else
		{
			$this->code = 500;
		}
		
		$this->data['forward'] = C('LtUrl')->generate('Ad', 'Index', array('template'=>$data['template']));
	}
}
